package com.jdk.demo.nio.bytebuffer;

import java.nio.ByteBuffer;

public class GetAndPut2 {

	public static void main(String[] args) {
		byte[] byteArrayIn1 = {1, 2, 3, 4, 5, 6, 7, 8};
		byte[] byteArrayIn2 = {55, 66, 77, 88};
		ByteBuffer bytebuffer = ByteBuffer.allocate(10);
		bytebuffer.put(byteArrayIn1); // 将1, 2, 3, 4, 5, 6, 7, 8放入缓冲区的前8个位置
		bytebuffer.position(2); // 执行put位置发生改变，将位置设置为2
		bytebuffer.put(byteArrayIn2, 1, 3); // 将数组55, 66, 77, 88中的66, 77, 88放入缓冲区的第3位，1代表byteArrayIn2的起始位置，3代表从1开始放入3个
		byte[] getByte = bytebuffer.array();
		for (int i = 0; i < getByte.length; i++) {
			System.out.print(getByte[i] + " ");
		}
		System.out.println(); // 1 2 66 77 88 6 7 8 0 0

		bytebuffer.position(1);
		// 创建新的byte[]数组byteArrayOut，目的是将缓冲区的数据导出来
		byte[] byteArrayOut = new byte[bytebuffer.capacity()];
		bytebuffer.get(byteArrayOut, 3, 4); // 使用get方法从缓冲区position为1位置开始，向byteArrayOut数组的索引为3处一共复制4个字节，3代表byteArrayOut的起始位置，4代表从3开始放入4个
		for (int i = 0; i < byteArrayOut.length; i++) {
			System.out.print(byteArrayOut[i] + " "); // 0 0 0 2 66 77 88 0 0 0
		}
		System.out.println();
		// 使用put时
		// 当offset+length的值大于src.length时，抛出IndexOutOfBoundsException
		// 当参数length的值大于buffer.remaining时，抛出BufferOverflowException
		// 使用get时
		// 当offset+length的值大于dst.length时，抛出IndexOutOfBoundsException
		// 当参数length的值大于buffer.remaining时，抛出BufferUnderflowException

		// 解决异常的方式
		m1();
		m2();
	}

	private static void m1() {
		byte[] byteArrayIn1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
		ByteBuffer bytebuffer = ByteBuffer.allocate(10);
		int getArrayIndex = 0;
		while(getArrayIndex < byteArrayIn1.length) {
			// 缓冲区的剩余和数组的剩余谁少
			int readLength = Math.min(bytebuffer.remaining(), byteArrayIn1.length - getArrayIndex);
			bytebuffer.put(byteArrayIn1, getArrayIndex, readLength);
			bytebuffer.flip();
			byte[] getArray = bytebuffer.array();
			for (int i = 0; i < bytebuffer.limit(); i++) {
				System.out.print(getArray[i] + " ");
			}
			System.out.println();
			getArrayIndex = getArrayIndex + readLength;
			bytebuffer.clear();
		}
	}

	private static void m2() {
		byte[] byteArrayIn = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
		ByteBuffer bytebuffer = ByteBuffer.wrap(byteArrayIn);
		byte[] byteArrayOut = new byte[5];
		while(bytebuffer.hasRemaining()) {
			// 缓冲区的剩余和数组的剩余谁少
			int readLength = Math.min(bytebuffer.remaining(), byteArrayOut.length);
			bytebuffer.get(byteArrayOut, 0, readLength);
			for (int i = 0; i < readLength; i++) {
				System.out.print(byteArrayOut[i] + " ");
			}
			System.out.println();
		}
	}

}
